package com.letv.core.network.volley;

import android.content.Context;
import android.net.http.AndroidHttpClient;
import android.os.Build;

import com.letv.core.download.image.DiskLruCache;
import com.letv.core.network.volley.listener.HttpStack;
import com.letv.core.network.volley.listener.Network;

import java.io.File;
import java.io.IOException;

/**
 * Volley
 * 
 * @author zhuqiao
 * 
 */
public class Volley {
    // 缓存最大容量
    private static final int MAX = 20 * 1024 * 1024;

    private static VolleyRequestQueue sQueue = null;
    private static Volley instance = null;
    private DiskLruCache mDiskLruCache;

//    private Volley() {
//        File cacheDir = BaseApplication.getInstance().getFilesDir();
//        if (cacheDir != null) {
//            if (!cacheDir.exists()) {
//                cacheDir.mkdirs();
//            }
//            mDiskLruCache = DiskLruCache.open(cacheDir, 1, 1, MAX);
//        }
//    }

    private Volley(Context mContext) {
        File cacheDir = mContext.getFilesDir();
        if (cacheDir != null) {
            if (!cacheDir.exists()) {
                cacheDir.mkdirs();
            }
            mDiskLruCache = DiskLruCache.open(cacheDir, 1, 1, MAX);
        }
    }

    public static VolleyRequestQueue getQueue() {
        if (sQueue == null) {
            sQueue = newRequestQueue();
        }
        return sQueue;
    }

//    public static Volley getInstance() {
//        if (instance == null) {
//            instance = new Volley();
//        }
//        return instance;
//    }

    public static Volley getInstance(Context mContext) {
        if (instance == null) {
            instance = new Volley(mContext);
        }
        return instance;
    }

    public DiskLruCache getDiskLurCache() {
        return mDiskLruCache;
    }

    public void flush() {
        if (mDiskLruCache != null) {
            try {
                mDiskLruCache.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private static VolleyRequestQueue newRequestQueue() {
        HttpStack stack;
        HttpStack fileStack = new HurlFileStack();

        if (Build.VERSION.SDK_INT >= 9) {
            stack = new HurlStack();
        } else {
            stack = new HttpClientStack(AndroidHttpClient.newInstance(""));
        }

        Network network = new BasicNetwork(stack);
        Network fileNetwork = new BasicNetwork(fileStack);

        VolleyRequestQueue queue = new VolleyRequestQueue(network, fileNetwork);
        queue.start();

        return queue;
    }

}
